import Vue from "vue";
import VueRouter from "vue-router";

const Login = () => import("components/common/Login/Login.vue");
const Home = () => import("components/common/Home/Home.vue");
const WellCome = () => import("components/common/Home/WellCome/WellCome.vue");
const User = () => import("components/common/User/Users.vue");
const Rights = () => import("components/common/Power/Rights.vue");
const Roles = () => import("components/common/Power/Roles.vue");
const Cate = () => import("components/common/Goods/Cate.vue");
const Params = () => import("components/common/Goods/Params.vue");
const List = () => import("components/common/Goods/List.vue")
const Add = () => import("components/common/Goods/Add.vue")

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: "/login",
    component: Login
  },
  {
    path: "/home",
    component: Home,
    redirect: "/wellcome",
    children: [
      {
        path: "/wellcome",
        component: WellCome
      },
      {
        path: "/users",
        component: User
      },
      {
        path: "/rights",
        component: Rights
      },
      {
        path: "/roles",
        component: Roles
      },
      {
        path: "/categories",
        component: Cate
      },
      {
        path: "/Params",
        component: Params
      },
      {
        path: "/goods",
        component: List
      },
      {
        path: "/goods/add",
        component: Add
      }
    ]
  }
];

const router = new VueRouter({
  routes,
  mode: "history"
});

//挂载路由前置守卫
/* 
  to：将要跳转的路径(未渲染)
  from: 从那个路径跳转而来
  next: 将要执行的函数
*/
router.beforeEach((to, from, next) => {
  if (to.path == "/login") return next(); //访问的如果是login页面，直接放行

  // 获取sessionStroage中的token值
  const tokenStr = window.sessionStorage.getItem("token");

  // 判断tokenStr是否为空，为空直接强行跳转到login页面
  // 此处最好将token发送到后台，由后台在数据库中查询该token是否正确再进行跳转
  if (!tokenStr) return next("/login");
  return next();
});

export default router;
